package com.gary.classLoad;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author peng_rui
 * @date 2022/4/4
 */
public class MyClassLoader extends ClassLoader{
    private String classPath;

    public MyClassLoader(String classPath) {
        this.classPath = classPath;
    }

    public MyClassLoader(ClassLoader parent, String classPath) {
        super(parent);
        this.classPath = classPath;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String fileName = classPath + name + ".class";
        BufferedInputStream bis = null;
        ByteArrayOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(fileName));
            byte[] data = new byte[1024];
            int len = 0;

            bos = new ByteArrayOutputStream();
            while ((len = bis.read(data)) != -1) {
                bos.write(data, 0, len);
            }

            byte[] bytes = bos.toByteArray();
            //defineClass() 加载类方法
            Class<?> aClass = defineClass(null, bytes, 0, bytes.length);
            return aClass;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                 if(bis != null) bis.close();
                 if(bos != null) bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
